﻿using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;
using System.Threading;
namespace taskmgr
{
	public partial class MainForm : Form
	{
		PerformanceCounter pmc=new PerformanceCounter();
		public MainForm()
		{
			int p=0;
			
			IntPtr ret=PSAPI.RtlAdjustPrivilege(PSAPI.SE_DEBUG_PRIVILEGE,true,false,out p);
			Debug.Print("debug:{0}",ret);
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
		void MainFormLoad(object sender, EventArgs e)
		{
			InitForm();
			//GetProcessList();
			this.notifyIcon1.Visible=true;
			notifyIcon1.Icon=this.Icon;
			//===
			pmc.CategoryName="Processor";
			pmc.CounterName="% Processor Time";
			pmc.InstanceName="_Total";
			pmc.MachineName=".";
			/*Thread th0=new Thread(new ParameterizedThreadStart(time0Tick));
			Thread th1=new Thread(new ParameterizedThreadStart(Timer1Tick));
			th0.IsBackground=true;
			th1.IsBackground=true;
			th0.Start();
			th1.Start();*/
			
		}
		//程序初始化
		void InitForm(){
			
			StatusPanel1.Width=Convert.ToInt32( this.Width*0.2);
			StatusPanel2.Width=Convert.ToInt32(this.Width*0.25);
			StatusPanel3.Width=Convert.ToInt32(this.Width*0.55);
			tabControl1.SelectedIndex=1;
			MnuNormalClick(null,null); //normal speed;
			//============================
			listView1.Columns.Add("program",250,HorizontalAlignment.Left);
			listView1.Columns.Add("status",150,HorizontalAlignment.Left);
			
			listView2.Columns.Add("Process name",120,HorizontalAlignment.Left);
			listView2.Columns.Add("pid ",50,HorizontalAlignment.Left);
			listView2.Columns.Add("Memory(KB)",60,HorizontalAlignment.Left);
			listView2.Columns.Add("path",210,HorizontalAlignment.Left);
			listView2.Columns.Add("IO",70,HorizontalAlignment.Left);
			//===================
			listView3.Columns.Add("item",150,HorizontalAlignment.Left);
			listView3.Columns.Add("path",250,HorizontalAlignment.Left);
			System.Windows.Forms.Timer timer0=new System.Windows.Forms.Timer();
			//Timer timer0=new Timer();
			timer0.Interval=2567;
			timer0.Enabled=true;
			timer0.Tick+=new EventHandler(time0Tick);
		}
		
		//系统进程
		void GetProcessList(){
			Hashtable list=new Hashtable();
			//pstable(list);
			PSAPI.GetList(list);
			StatusPanel1.Text="process:"+ Convert.ToString(list.Count);
			for(int i=0;i<=listView2.Items.Count-1;i++){
				string sid=listView2.Items[i].Name;
				sid=sid.Replace("pid","");
				int pid=Convert.ToInt32(sid);
				if(list.Contains(pid)){ //已存在,修改数据
					list.Remove(pid);
					uint mm=PSAPI.GetMemorySize(pid); //memory
					listView2.Items[i].SubItems[2].Text =string.Format("{0:0,0}", mm/1024);
					ulong ioc=PSAPI.GetIOCount(pid,4);
					listView2.Items[i].SubItems[4].Text=string.Format("{0:0,0}",ioc);
				}else{
					listView2.Items[i].Remove();					
					imageList1.Images[i].Dispose();
				}
			}
			if(list.Count==0){
				return;
			}
			int ii=imageList1.Images.Count;
			foreach(int key in list.Keys){
				ListViewItem lv=new ListViewItem();
				lv.Text =(string) list[key];
				int pid=key;
				lv.Name="pid"+ Convert.ToString(pid) ;
				uint mem=PSAPI.GetMemorySize(pid)/1024;
				
				string fpath=PSAPI.ConvertPath(PSAPI.GetPathEx(pid)); //file path
				string pn=SystemInfo.GetFileInfo(fpath,1);
				if(pn.ToLower()=="microsoft corporation" | fpath=="NT Kernel"){
					lv.ForeColor=Color.Black;
				}else{
					lv.ForeColor=Color.Blue;
				}
				ulong ioc=PSAPI.GetIOCount(pid,4);	
				Icon fi=Win32.GetIcon(fpath);
				
				imageList1.Images.Add(fi);
				
				lv.ImageIndex=ii;
				ii+=1;
				//Win32.SHFILEINFO sfi;
				//Win32.SHGetFileInfo(fpath,0,sfi,Marshal.SizeOf(sfi),0x1);
				
				lv.SubItems.Add(Convert.ToString(pid));
				lv.SubItems.Add(string.Format("{0:0,0}", mem));
				lv.SubItems.Add(fpath);
				lv.SubItems.Add(Convert.ToString(ioc));
				listView2.Items.Add(lv);
				//Win32.DestroyIcon(fi.Handle);
			}
			GC.Collect(); 
		}
		//窗体
		void GetWindowList(){
			Hashtable list=new Hashtable();
			window.GetList(list);
			StatusPanel1.Text="windows:"+Convert.ToString(list.Count);
			if(listView1.Items.Count>0){
			for(int i=0;i<=listView1.Items.Count-1;i++){
				string shwnd=listView1.Items[i].Name;
				shwnd=shwnd.Replace("hwnd","");
				int ihwnd=Convert.ToInt32(shwnd);
				IntPtr hwnd=new IntPtr(ihwnd);
				if(list.Contains(hwnd)){ //if hashtable is exist
					list.Remove(hwnd);
					if(window.IsHungAppWindow(hwnd)){
						listView1.Items[i].SubItems[1].Text="未响应";
					}else{
						listView1.Items[i].SubItems[1].Text="正在运行";
					}
				}else{
					listView1.Items[i].Remove();
				}
			}
			}
			
			foreach(IntPtr key in list.Keys) {
				ListViewItem lv=new ListViewItem();
				lv.Name="hwnd"+ key.ToString();
				lv.Text=(string) list[key];
				
				if(window.IsHungAppWindow(key)==false){
					lv.SubItems.Add("正在运行");
				}else{
					lv.SubItems.Add("未响应");
				}
				listView1.Items.Add(lv);
			}
		
		}
		
		void GetRunItem(){
			
		}
			
		void TabControl1SelectedIndexChanged(object sender, EventArgs e)
		{
			switch(tabControl1.SelectedIndex){
				case 0:
					GetWindowList();
					break;
				case 1:
					GetProcessList();
					break;
			}
		}
		
		void SetNotifyIcon(int index,string ntext){
			try{
				Image img =this.imageList2.Images[index];
				Bitmap bm=new Bitmap(img);
				Icon icon=Icon.FromHandle(bm.GetHicon());
				this.notifyIcon1.Icon=icon;
				this.notifyIcon1.Text=ntext;
				icon.Dispose();
			}
			catch(Exception ex){
				Debug.Print(ex.ToString());
			}	
		}
		void time0Tick(object sender,EventArgs e){
			float c=pmc.NextValue();
			int cpu=(int)c;
			string scpu="CPU Usage: {0:d}%";
			StatusPanel2.Text=string.Format(scpu,cpu);
			//fuck !!i don't know how to code switch 
			if(cpu<10){
				SetNotifyIcon(0,string.Format(scpu,cpu));
			}else if(10<cpu && cpu<20){
				
				SetNotifyIcon(1,string.Format(scpu,cpu));
			}else if(20<cpu && cpu<30){
				
				SetNotifyIcon(2,string.Format(scpu,cpu));
			}else if(30<cpu && cpu<40){
				SetNotifyIcon(3,string.Format(scpu,cpu));
			}else if(40<cpu && cpu<50){
				SetNotifyIcon(4,string.Format(scpu,cpu));
			}else if(50<cpu && cpu<60){
				SetNotifyIcon(5,string.Format(scpu,cpu));
			}else if(60<cpu && cpu<70){
				SetNotifyIcon(6,string.Format(scpu,cpu));
			}else if(70<cpu && cpu<80){
				SetNotifyIcon(7,string.Format(scpu,cpu));
			}else if(cpu>80){
				SetNotifyIcon(8,string.Format(scpu,cpu));
			}
		}
		void Timer1Tick(object sender, EventArgs e)
		{
			switch(tabControl1.SelectedIndex){
				case 0:
					GetWindowList();
					break;
				case 1:
					GetProcessList();
					break;
			}
		}
		//快
		void MnuHighClick(object sender, EventArgs e)
		{
			timer1.Interval=500;
			mnuHigh.Checked=true;
			mnuNormal.Checked=false;
			mnuSlow.Checked=false;
			mnuPause.Checked=false;
		}
		//标准速度
		void MnuNormalClick(object sender, EventArgs e)
		{
			timer1.Interval=2000;
			mnuHigh.Checked=false;
			mnuNormal.Checked=true;
			mnuSlow.Checked=false;
			mnuPause.Checked=false;
		}
		//慢
		void MnuSlowClick(object sender, EventArgs e)
		{
			timer1.Interval=3500;
			mnuHigh.Checked=false;
			mnuNormal.Checked=false;
			mnuSlow.Checked=true;
			mnuPause.Checked=false;
		}
		
		void MnuPauseClick(object sender, EventArgs e)
		{
			timer1.Enabled=false;
			mnuHigh.Checked=false;
			mnuNormal.Checked=false;
			mnuSlow.Checked=false;
			mnuPause.Checked=true;
		}
		
		void AboutToolStripMenuItemClick(object sender, EventArgs e)
		{
			StatusPanel3.Text=Convert.ToString(PSAPI.RunTime(400));
		}
		//窗体改变
		void MainFormSizeChanged(object sender, EventArgs e)
		{
			if(WindowState==FormWindowState.Minimized){
				if(mnuHideForm.Checked==true){
					this.Hide();
					this.ShowInTaskbar=false;
				}
				notifyIcon1.Visible=true;
			}
			try{
				int fwidth=this.Width;
				int fheight=this.Height;
				tabControl1.Width=fwidth-10;
				tabControl1.Height=fheight-30;
				listView1.Width=tabControl1.Width-20;
				listView1.Height=tabControl1.Height-90;
				listView2.Width=tabControl1.Width-20;
				listView2.Height=tabControl1.Height-90;
				button1.Left=(int)(fwidth/2);
				button1.Top=statusStrip1.Top+20;
				
			}catch{
				return;
			}	
		}
			
		//hide form in tasker
		void MnuHideFormClick(object sender, EventArgs e)
		{
			if(mnuHideForm.Checked){
				mnuHideForm.Checked=false;
				this.ShowInTaskbar=false;
			}else{
				mnuHideForm.Checked=true;
				this.ShowInTaskbar=true;
			}
		}
		//托盘双击
		void NotifyIcon1DoubleClick(object sender, EventArgs e)
		{
			this.Visible=true;
			this.WindowState=FormWindowState.Normal;
		}
		//进程listview
		void ListView2MouseUp(object sender, MouseEventArgs e)
		{
			if(e.Button==MouseButtons.Right && listView2.SelectedItems.Count>0 ){
				lvw2Menu.Show(listView2,e.Location);
				ListViewItem lv=listView2.SelectedItems[0];
				if(lv.ForeColor==Color.Gray){ //suspend
					mnuProcessSuspend.Text="进程继续";
				}else{
					mnuProcessSuspend.Text="进程挂起";
				}
			}
		}
		//terminate process
		void MnuTerminateProcessClick(object sender, EventArgs e)
		{
			string sid= listView2.SelectedItems[0].Name;
			sid=sid.Replace("pid","");
			int pid=Convert.ToInt32(sid);
			if(PSAPI.EndProcess(pid)){
				listView2.SelectedItems[0].Remove();
			}else{
				MessageBox.Show("terminate process error","fail",MessageBoxButtons.OK,
				               MessageBoxIcon.Warning);
			}
		}
		
		void NotifyIcon1MouseDoubleClick(object sender, MouseEventArgs e)
		{
			
		}
		//suspend process
		void ToolStripMenuItem3Click(object sender, EventArgs e)
		{
			ListViewItem lv=listView2.SelectedItems[0];
			string sid=lv.Name;
			sid=sid.Replace("pid","");
			int pid=Convert.ToInt32(sid);
			if(pid==0|pid==4){
				MessageBox.Show("系统内核不要乱挂,万一系统跟着挂","Warning",MessageBoxButtons.OK,
				                MessageBoxIcon.Warning);
				return;
			}
			if(mnuProcessSuspend.Text=="进程挂起"){
				if(PSAPI.Suspend(pid,true)==false){
					MessageBox.Show("suspend error","warning",
					                MessageBoxButtons.OK,MessageBoxIcon.Warning);
					
				}else{
					lv.ForeColor=Color.Gray;
				}
			}else{
				PSAPI.Suspend(pid,false);
				lv.ForeColor=Color.Black;
			}
		}
		
		void MnuPowerShutdownClick(object sender, EventArgs e)
		{
			SystemInfo.PowerShutdown(0);
		}
		
		void MenuStrip_ExitClick(object sender, EventArgs e)
		{
			Application.Exit();
		}
		
		//
		void MnuLoadModulesClick(object sender, EventArgs e)
		{
			ListViewItem lv=listView2.SelectedItems[0];
			string sid=lv.Name;
			sid=sid.Replace("pid","");
			int pid=Convert.ToInt32(sid);
			
			frmdll frm=new frmdll();
			frm.ProcID=pid;
			frm.Show();
			
		}
		
		
		void mnuTDeleteClick(object sender, EventArgs e)
		{
			if(MessageBox.Show("are you sure","terminate and delete file",MessageBoxButtons.YesNo,
			                   MessageBoxIcon.Warning)== DialogResult.Yes){
				ListViewItem lv=listView2.SelectedItems[0];
				string sid=lv.Name;
				sid=sid.Replace("pid","");
				int pid=Convert.ToInt32(sid);
				if(pid==0|pid==4){
					MessageBox.Show("don't luangao");
					return;
				}
				if(PSAPI.EndProcess(pid)){
					string fpath=PSAPI.GetPathEx(pid);
					fpath=PSAPI.ConvertPath(fpath);
					Thread.Sleep(1000);
					if(SystemInfo.DeleteFile(fpath)==false){
						MessageBox.Show("delete file fail","warning",MessageBoxButtons.OK,
						                MessageBoxIcon.Warning);
					}
				}
			}
		}
			
		void mnusetFormTopClick(object sender, EventArgs e)
		{
			if(mnuSetFormTop.Checked){
				this.TopMost=false;
				mnuSetFormTop.Checked=false;
			}else{
				this.TopMost=true;
				mnuSetFormTop.Checked=true;
			}
		}
		
		void AboutToolStripMenuItem1Click(object sender, EventArgs e)
		{
			
			
		}
		//process id menu
		void MnuPIDClick(object sender, EventArgs e)
		{
			if(mnuPID.Checked ){ //false
				listView2.Columns[1].Width=0;
				mnuPID.Checked=false;
			}else{
				mnuPID.Checked=true;
				listView2.Columns[1].Width=60;
			}
			
		}
		
		void MnuProcIOClick(object sender, EventArgs e)
		{
			if(mnuProcIO.Checked){
				listView2.Columns[4].Width=0;
				mnuProcIO.Checked=false;
			}else{
				mnuProcIO.Checked=true;
				listView2.Columns[4].Width=70;
			}
		}
		
		void MnuProcPathClick(object sender, EventArgs e)
		{
			if(mnuProcPath.Checked){
				listView2.Columns[3].Width=0;
				mnuProcPath.Checked=false;
			}else{
				mnuProcPath.Checked=true;
				listView2.Columns[3].Width=70;
			}
		}
		
		void MnuWinSwitchClick(object sender, EventArgs e)
		{
			ListViewItem lv=listView1.SelectedItems[0];
			string shwnd=lv.Name;
			shwnd=shwnd.Replace("hwnd","");
			int ihwnd=Convert.ToInt32(shwnd);
			IntPtr hwnd=new IntPtr(ihwnd);
			int pid=window.HWND2PID(hwnd);
			Debug.Print("pid:{0}",pid);
			string spid="pid"+ pid.ToString();
			for(int i=0;i<listView2.Items.Count;i++){
				if(listView2.Items[i].Name==spid){
					tabControl1.SelectedIndex=1;
					listView2.Items[i].Selected=true;
					break;
				}
			}
		}
		
		void ListView1MouseUp(object sender, MouseEventArgs e)
		{
			if(e.Button==MouseButtons.Right && listView1.SelectedItems.Count>0){
				lvw1Menu.Show(listView1,e.Location);
			}
		}
		
		void MnuWinTerminateClick(object sender, EventArgs e)
		{
			ListViewItem lv=listView1.SelectedItems[0];
			string shwnd=lv.Name;
			shwnd=shwnd.Replace("hwnd","");
			int ihwnd=Convert.ToInt32(shwnd);
			IntPtr hwnd=new IntPtr(ihwnd);
			int pid=window.HWND2PID(hwnd);
			if(PSAPI.EndProcess(pid)){
				lv.Remove();
			}else{
				MessageBox.Show("terminate error","warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
				
			}
		}
		
		//定位文件
		void LocationFileToolStripMenuItemClick(object sender, EventArgs e)
		{
			ListViewItem lv=listView2.SelectedItems[0];
			string p=lv.Name;
			p=p.Replace("pid","");
			int pid=Convert.ToInt32(p);
			if(pid==0 | pid==4){
				return;
			}
			string f=PSAPI.GetPathEx(pid);
			SystemInfo.ShowFileLocation(f);
		}
		
		//文件属性
		void PropertyFileToolStripMenuItemClick(object sender, EventArgs e)
		{
			ListViewItem lv=new ListViewItem();
			lv=listView2.SelectedItems[0];
			string p=lv.Name;
			p=p.Replace("pid","");
			int pid=Convert.ToInt32(p);
			if(pid==0|pid==4){
				return ;
			}
			string f=PSAPI.GetPathEx(pid);
			Debug.Print("shellexecuteex:{0}",SystemInfo.ShowPropertyFile(f,this.Handle));
			
		}
		//notify show form
		void ShowToolStripMenuItemClick(object sender, EventArgs e)
		{
			WindowState=FormWindowState.Normal;
		}
		//notify menu exit application
		void ExitToolStripMenuItemClick(object sender, EventArgs e)
		{
			this.Dispose();
			this.Close();
		}
		
		void MenuStrip_ShutdownClick(object sender, EventArgs e)
		{
			int p=0;
			IntPtr ret=PSAPI.RtlAdjustPrivilege(PSAPI.SE_SHUTDOWN_PRIVILEGE,true,false,out p);
			Debug.Print("shutdown privilege:{0}",ret);
			SystemInfo.Shutdown(SystemInfo.EWX_SHUTDOWN|SystemInfo.EXW_FORCE);
		}
		
		void MnuWinSetForeClick(object sender, EventArgs e)
		{
			ListViewItem lv=new ListViewItem();
			lv=listView1.SelectedItems[0];
			string ch=lv.Name;
			ch=ch.Replace("hwnd","");
			int ih=Convert.ToInt32(ch);
			IntPtr hwnd=new IntPtr(ih);
			window.Setfore(hwnd);
			
		}
	}
}
